import React from "react";
import { connect } from "react-redux";
import { omit, pick } from "lodash";
import { materialConfig } from "visbar-component";
import BlueprintFactory from "../../lib/blueprintFactory";
import Wrapper from "../../layout/Wrapper";
import ReactForEcharts from "../../components/ReactForEcharts";
import { IEditorState as IEditorReducerState } from "../../store/reducers/editor";
import { DATASOURCE_KEY } from "../../store/constants";
import echartsEventAndAction from "../../constants/echarts-config/eventAndAction.json";
import "./index.scss";

interface BaseVisbarPagePreviewProps {}
type VisbarPagePreviewProps = BaseVisbarPagePreviewProps & IEditorReducerState;
class VisbarPagePreview extends React.Component<VisbarPagePreviewProps> {
  private blueprint = BlueprintFactory.getBlueprintInstance();
  constructor(props: VisbarPagePreviewProps) {
    super(props);
    this.blueprint.setOptions(props.blueprint);
  }
  renderBaseComponent = (nodeName: string, config: any) => {
    const Node = require("visbar-component")[nodeName];
    if (!Node) return <p>当前物料控件不存在，请联系管理员添加...</p>
    const nodeEvents = (materialConfig as any)[nodeName]?.eVisbar.event;
    const eventsFuncMap = this.generatorCompEvents(nodeEvents, config);
    return <Node {...config.props} style={config.style}
      { ...eventsFuncMap }
      ref={(ref: any) => this.blueprint?.registerCompInstance(config.id, ref)} />
  }
  generatorCompEvents = (events: any, config: any) => {
    const eventsMap = {};
    Object.keys(events || {}).forEach(key => {
      const currentEvent = (events as any)[key];
      const eventName = currentEvent.eventName || key;
      Reflect.set(eventsMap, eventName, this.blueprint.wrapperEventFactory(config.id, key));
    });
    return eventsMap;
  }
  render() {
    const { components, pageProps } = this.props;
    const baseSize = pick(pageProps.style, ["width", "height"]);
    return <div className="visbar-preview-container" style={omit(pageProps.style, ["width", "height"])}>
      {components.map(conf => <Wrapper key={conf.id}
        style={conf.style}
        id={conf.id} baseSize={baseSize}>
        {
          conf.node
            ? this.renderBaseComponent(conf.node, conf)
            : <ReactForEcharts options={conf.props}
                dataSourceConfig={conf.dataSource?.[DATASOURCE_KEY] || []}
                geoMap={conf.dataSource?.geoMap || []}
                ref={(ref: any) => this.blueprint?.registerCompInstance(conf.id, ref)}
                eventsMap={this.generatorCompEvents(echartsEventAndAction.event, conf)}
              />
        }
      </Wrapper>)}
    </div>
  }
}

export default connect((state: any) => state.editor)(VisbarPagePreview);